package com.yaodian100.mall.member.web;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.coupon.entity.Coupon;
import com.yaodian100.ec.coupon.entity.CouponItem;
import com.yaodian100.ec.coupon.service.CouponService;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;

/**
 * 我的禮卷
 * 
 * @author apple.chang
 * 
 */
public class MyCouponAction extends ActionSupport {

	public static final String COUPON_LIST_TYPE_WAIT_COUPON = "waitCoupon";
	public static final String COUPON_LIST_TYPE_USABLE_COUPON = "usableCoupon";

	private static final char CATEGORY_PATH_SEPARATOR = '/';
	private static final String RESULT_VIEW_COUPON_APPLY_RANGE = "viewCouponApplyRange";
	private static final String RESULT_TO_GET_COUPON = "togetcoupon";

	private static final long serialVersionUID = 8869900313030803419L;

	private MemberService memberService;
	private CouponService couponService;

	@Autowired
	private CategoryService categoryService;
	// 供頁面查詢商品名稱
	@Autowired
	private ProductService productService;
	// 用於判斷適用商品會員價是否高於最低商品價格
	@Autowired
	private ShelfService shelfService;

	private List<CouponItem> couponList;
	private List<String> applicableItemIdList;

	private Member member;
	private BigDecimal canUse;
	private String nearlyD;
	private String nearlyValue;
	private String lastCouponCode;
	private String couponItemCode;
	private int canUseCoupon;
	/**
	 * 優惠碼是否錯誤
	 */
	private boolean couponItemCodeError;
	/**
	 * 優惠碼已充值
	 */
	private boolean couponItemRegistered;
	/**
	 * 優惠碼過期
	 */
	private boolean couponExpired;
	/**
	 * 禮券限制一人最多一張優惠碼，而會員已經取得過
	 */
	private boolean noMoreCouponItemAllowedForCurrentCoupon;
	/**
	 * 優惠碼充值成功
	 */
	private boolean couponRegisterSuccess;

	private Coupon coupon;

	/**
	 * 禮券列表類別（可用禮券、待生效禮券）
	 */
	private String couponListType;

	/**
	 * 我的禮卷
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String tomycoupon() throws CoreException {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId(), request.getServerName());
		couponList = couponService.getListItems(member.getMemberId());
		canUseCoupon = 0;
		canUse = new BigDecimal(0);
		if (null == couponList || couponList.size() == 0) {
			nearlyD = "";
		} else {
			CouponItem lastCoupon = couponList.get(0);
			for (CouponItem coupon : couponList) {
				if (coupon.getStartDate().getTime() <= System.currentTimeMillis()
						&& coupon.getEndDate().getTime() > System.currentTimeMillis()) {
					canUseCoupon++;
					canUse = canUse.add(coupon.getCoupon().getFaceValue());
					if (lastCoupon.getEndDate().getTime() <= System.currentTimeMillis()
							|| (coupon.getEndDate().getTime() < lastCoupon.getEndDate().getTime())) {
						lastCoupon = coupon;
					}
				}
			}
			if (lastCoupon.getEndDate().getTime() <= System.currentTimeMillis()) {
				nearlyD = "";
			} else {
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				nearlyD = dateFormat.format(lastCoupon.getEndDate());
				nearlyValue = lastCoupon.getCoupon().getFaceValue().toString();
				lastCouponCode = lastCoupon.getCode();
			}
		}
		setCouponListType(COUPON_LIST_TYPE_USABLE_COUPON);
		return "tomycoupon";
	}

	/**
	 * 目前可用礼券
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String accumulatecoupon() throws CoreException {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId(), request.getServerName());
		couponList = couponService.getListItems(member.getMemberId());
		setCouponListType(COUPON_LIST_TYPE_USABLE_COUPON);
		return "accumulatecoupon";
	}

	/**
	 * 待生效礼券
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String waitcoupon() throws CoreException {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId(), request.getServerName());
		couponList = couponService.getWaitItems(member.getMemberId());
		setCouponListType(COUPON_LIST_TYPE_WAIT_COUPON);
		return "waitcoupon";
	}

	/**
	 * 使用明細
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String tousecoupon() throws CoreException {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId(), request.getServerName());
		couponList = couponService.getUsedItems(member.getMemberId());
		return "tousecoupon";
	}

	/**
	 * @author chin.hung
	 */
	public String togetcoupon() throws CoreException {
		return RESULT_TO_GET_COUPON;
	}

	/**
	 * @author chin.hung
	 */
	public String gettingCoupon() throws CoreException {
		String couponItemCode = getCouponItemCode();
		couponItemCode = StringUtils.trimToNull(couponItemCode);

		if (StringUtils.isEmpty(couponItemCode)) {
			// 告訴頁面優惠碼錯誤
			setCouponItemCodeError(true);
			return RESULT_TO_GET_COUPON;
		}
		if (couponItemCode.length() != 10) {
			// 告訴頁面優惠碼錯誤
			setCouponItemCodeError(true);
			return RESULT_TO_GET_COUPON;
		}

		CouponItem couponItem = couponService.getCouponItemByCode(couponItemCode);
		if (couponItem == null) {
			// 告訴頁面優惠碼錯誤
			setCouponItemCodeError(true);
			return RESULT_TO_GET_COUPON;
		}
		if (couponItem.getMemberId() != null) {
			// 告訴頁面優惠碼已充值
			setCouponItemRegistered(true);
			return RESULT_TO_GET_COUPON;
		}
		Coupon coupon = couponItem.getCoupon();
		Date now = new Date();
		if (couponItem.getEndDate().before(now)) {
			// 告訴頁面優惠已過期
			setCouponExpired(true);
			return RESULT_TO_GET_COUPON;
		}
		if (Coupon.Status.INACTIVE.equals(coupon.getStatus())) {
			// 告訴頁面優惠已過期
			setCouponExpired(true);
			return RESULT_TO_GET_COUPON;
		}

		// 抓取會員
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId(), request.getServerName());

		// 該禮券是否不允許同一會員取得多張優惠碼
		if (coupon.getIsOnce().booleanValue()) {
			List<CouponItem> couponItemsOfMember = this.couponService.getCouponItemListByCouponAndMember(coupon, member);
			if (couponItemsOfMember != null && couponItemsOfMember.size() > 0) {
				// 告訴頁面會員已經取得優惠，且該禮券同一會員不能取得多張優惠碼
				setNoMoreCouponItemAllowedForCurrentCoupon(true);
				return RESULT_TO_GET_COUPON;
			}
		}

		// 進行充值
		String memberId = member.getMemberId();
		couponService.regCouponItem(couponItem, memberId);
		setCouponRegisterSuccess(true);

		return accumulatecoupon();
	}

	public String viewCouponApplyRange() {
		CouponItem couponItem = couponService.getCouponItemByCode(couponItemCode);
		Coupon coupon = couponItem.getCoupon();
		Coupon.ApplyRangType applyRangeType = coupon.getApplyRangeType();

		if (applyRangeType.equals(Coupon.ApplyRangType.ALL)) {
			setCoupon(couponItem.getCoupon());
			return RESULT_VIEW_COUPON_APPLY_RANGE;
		}

		List<String> applicableItemIdList = new ArrayList<String>();

		String[] applyRangeExtensionArray = coupon.getApplyRangeTypeExtensionArray();
		for (String applyRangeExtension : applyRangeExtensionArray) {
			switch (applyRangeType) {
			case CATEGORY:
				String categoryPath = applyRangeExtension;
				String[] categoryPathArray = StringUtils.split(categoryPath, CATEGORY_PATH_SEPARATOR);

				if (categoryPathArray == null) {
					break;
				}
				if (categoryPathArray.length <= 0) {
					break;
				}
				String categoryIdString = categoryPathArray[categoryPathArray.length - 1];
				if (!StringUtils.isNumeric(categoryIdString)) {
					break;
				}

				Long categoryId = Long.parseLong(categoryIdString);

				// 檢查分類是否存在
				Category category = categoryService.getCategoryById(categoryId);
				if (category == null) {
					break;
				}

				if (!categoryPath.equals(category.getCategoryPath())) {
					break;
				}

				applicableItemIdList.add(categoryIdString);
				break;
			case PRODUCT:
				String productId = applyRangeExtension;

				Product product = productService.get(productId);
				// 檢查商品是否存在
				if (product == null) {
					break;
				}

				Shelf shelf = getShelfService().getActiveShelfByProductId(productId);
				// 檢查是否有上架檔
				if (shelf == null) {
					break;
				}

				// 檢查是否有價格
				if (shelf.getShelfPrice() == null) {
					break;
				}

				// 檢查商品價格是否大於等於最低商品價格
				if (shelf.getShelfPrice().doubleValue() < coupon.getMinimumProductPrice().doubleValue()) {
					break;
				}

				applicableItemIdList.add(productId);
				break;
			}
		}

		setApplicableItemIdList(applicableItemIdList);
		setCoupon(couponItem.getCoupon());
		return RESULT_VIEW_COUPON_APPLY_RANGE;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public CategoryService getCategoryService() {
		return this.categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public BigDecimal getCanUse() {
		return canUse;
	}

	public void setCanUse(BigDecimal canUse) {
		this.canUse = canUse;
	}

	public String getNearlyD() {
		return nearlyD;
	}

	public void setNearlyD(String nearlyD) {
		this.nearlyD = nearlyD;
	}

	public String getNearlyValue() {
		return nearlyValue;
	}

	public void setNearlyValue(String nearlyValue) {
		this.nearlyValue = nearlyValue;
	}

	public void setCouponService(CouponService couponService) {
		this.couponService = couponService;
	}

	public ProductService getProductService() {
		return this.productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public List<CouponItem> getCouponList() {
		return couponList;
	}

	public void setCouponList(List<CouponItem> couponList) {
		this.couponList = couponList;
	}

	public List<String> getApplicableItemIdList() {
		return this.applicableItemIdList;
	}

	public void setApplicableItemIdList(List<String> applicableItemIdList) {
		this.applicableItemIdList = applicableItemIdList;
	}

	public String getLastCouponCode() {
		return lastCouponCode;
	}

	public void setLastCouponCode(String lastCouponCode) {
		this.lastCouponCode = lastCouponCode;
	}

	public String getCouponItemCode() {
		return this.couponItemCode;
	}

	public void setCouponItemCode(String couponItemCode) {
		this.couponItemCode = couponItemCode;
	}

	public boolean isCouponItemCodeError() {
		return this.couponItemCodeError;
	}

	/**
	 * 設定為 private，不讓外界更動此屬性質
	 */
	private void setCouponItemCodeError(boolean coupondItemCodeError) {
		this.couponItemCodeError = coupondItemCodeError;
	}

	public boolean isCouponItemRegistered() {
		return this.couponItemRegistered;
	}

	/**
	 * 設定為 private，不讓外界更動此屬性質
	 */
	private void setCouponItemRegistered(boolean couponItemRegistered) {
		this.couponItemRegistered = couponItemRegistered;
	}

	public boolean isCouponExpired() {
		return this.couponExpired;
	}

	/**
	 * 設定為 private，不讓外界更動此屬性質
	 */
	private void setCouponExpired(boolean couponExpired) {
		this.couponExpired = couponExpired;
	}

	public boolean isCouponRegisterSuccess() {
		return this.couponRegisterSuccess;
	}

	/**
	 * 設定為 private，不讓外界更動此屬性質
	 */
	public void setCouponRegisterSuccess(boolean couponRegisterSuccess) {
		this.couponRegisterSuccess = couponRegisterSuccess;
	}

	public Coupon getCoupon() {
		return this.coupon;
	}

	/**
	 * 設定為 private，不讓外界更動此屬性質
	 */
	private void setCoupon(Coupon coupon) {
		this.coupon = coupon;
	}

	public ShelfService getShelfService() {
		return this.shelfService;
	}

	public void setShelfService(ShelfService shelfService) {
		this.shelfService = shelfService;
	}

	public String getCouponListType() {
		return this.couponListType;
	}

	public void setCouponListType(String couponListType) {
		this.couponListType = couponListType;
	}

	public boolean isNoMoreCouponItemAllowedForCurrentCoupon() {
		return this.noMoreCouponItemAllowedForCurrentCoupon;
	}

	public void setNoMoreCouponItemAllowedForCurrentCoupon(boolean noMoreCouponItemAllowedForCurrentCoupon) {
		this.noMoreCouponItemAllowedForCurrentCoupon = noMoreCouponItemAllowedForCurrentCoupon;
	}

	public int getCanUseCoupon() {
		return canUseCoupon;
	}

	public void setCanUseCoupon(int canUseCoupon) {
		this.canUseCoupon = canUseCoupon;
	}

}